﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using app.Models;
using AmuTools;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace app.Api
{
    /*
      
    */
    public class ApiLogin : ApiBase
    {
        public ApiLogin(Controller ctx) : base(ctx)
        {
        }

        #region 自定义请求参数
        // Admin
        int req_role_id { get { return GetIntParam(new ReqIntParamOption { Name = "role_id", Level = REQPARAMLEVEL.FREE }); } }
        #endregion

        public void Admin(string action)
        {
            switch(action)
            {
                case "login":
                    {
                        string validate_code = ctx.Session["validate_code"].ToString();
                        string code = GetStringParam(new ReqStringParamOption { Name = "validate_code" }).ToUpper();
                        if (code.Equals(validate_code))
                        {
                            ResponseJson(Login(IDENTITY.ADMIN));
                        }
                        else
                        {
                            ResponseJson(new BooleanResult { value = false, message = "验证码错误" });
                        }
                        return;
                    }
                case "logout":
                    {
                        Logout();
                        ResponseJson(new Result());
                        return;
                    }
            }

            // 这是个特殊的检测权限函数，说明需要检测是不是管理员身份
            CheckPermission(IDENTITY.ADMIN);
            Admin admin = null;
            switch (action)
            {
                case "add":
                    {
                        //admin 添加
                        CheckPermission(IDENTITY.ADMIN, Permission.Module(PERMISSIONMODULE.ADMIN_MANAGE).Add());
                        if (G.DB.IsOne<Admin>(string.Format("username='{0}'", req_username))) ThrowStatus(STATUS.FAILED_INSERT, "用户名已存在");
                        admin = new Admin { username = req_username, password = HashHelper.Hash_MD5_16(req_password), role_id = req_role_id };
                        G.DB.Insert<Admin>(admin);
                        ResponseJson(new IDResult { id = admin.id });
                        RecordLog(PERMISSIONOPERATION.ADD, UserName + "添加管理员：" + req_username);
                        break;
                    }
                case "modify":
                    {
                        CheckPermission(IDENTITY.ADMIN, Permission.Module(PERMISSIONMODULE.ADMIN_MANAGE).Modify());
                        admin = G.DB.GetById<Admin>(req_id);
                        admin.username = req_username;
                        if (req_password != "******") admin.password = HashHelper.Hash_MD5_16(req_password);
                        admin.role_id = req_role_id;
                        if (G.DB.Update<Admin>(admin) == 0)
                        {
                            ThrowStatus(STATUS.FAILED_UPDATE, "*管理员账户更新失败！");
                        }
                        else
                        {
                            ResponseJson(new Result());
                            RecordLog(PERMISSIONOPERATION.MODIFY, UserName + "修改管理员：" + req_username + "的账号信息。");
                        }
                        break;
                    }
                case "delete":
                    {
                        CheckPermission(IDENTITY.ADMIN, Permission.Module(PERMISSIONMODULE.ADMIN_MANAGE).Delete());
                        if (G.DB.Delete<Admin>(req_id) == 0)
                        {
                            ThrowStatus(STATUS.FAILED_DELETE, "*管理员账户删除失败！");
                        }
                        else
                        {
                            ResponseJson(new Result());
                            RecordLog(PERMISSIONOPERATION.DELETE, UserName + "删除管理员：" + req_username + "的账号信息");
                        }
                        break;
                    }
                // 用户自己修改密码
                case "update_pwd":
                    {
                        string old_password = GetStringParam(new ReqStringParamOption { Name = "old_password" });
                        string new_password = GetStringParam(new ReqStringParamOption { Name = "new_password" });
                        admin = G.DB.GetById<Admin>(UserCode);
                        if (HashHelper.Hash_MD5_16(old_password) == admin.password)
                        {
                            admin.password = HashHelper.Hash_MD5_16(new_password);
                            G.DB.Update<Admin>(admin);
                            ResponseJson(new Result());
                            RecordLog(PERMISSIONOPERATION.MODIFY, UserName + "重置自己的账号密码。");
                        }
                        else
                        {
                            ThrowStatus(STATUS.FAILED_UPDATE, "原始密码输入错误，密码重置失败");
                        }
                        break;
                    }
                case "overview":
                    {
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic["unProcessed_count"] = G.DB.GetCount<Feedback>(string.Format("status = {0}", (int)FEEDBACK_SATTUS.UNPROCESSED));
                        dic["firm_examining_count"] = G.DB.GetCount<Member>(string.Format("status = {0} and role_type = {1}", (int)AUTH_STATUS.EXAMINING, (int)ROLE_TYPES.ENTERPRISE));
                        dic["service_register_examining_count"] = G.DB.GetCount<Member>(string.Format("status = {0} and role_type = {1}", (int)AUTH_STATUS.EXAMINING, (int)ROLE_TYPES.SERVICE));
                        dic["member_count"] = G.DB.GetCount<Member>(string.Format("status = {0}", (int)AUTH_STATUS.EXAMINING));
                        dic["service_count"] = G.DB.GetCount<ServiceItem>(string.Format("status = {0}", (int)SERVICE_STATUS.EXAMINING));
                        dic["demand_examining_count"] = G.DB.GetCount<DemandItem>(string.Format("status = {0}", (int)DEMAND_STATUS.EXAMINING));

                        dic["unProcessed_totalcount"] = G.DB.GetCount<Feedback>();
                        dic["firm_examining_totalcount"] = G.DB.GetCount<Member>(string.Format("role_type = {0}", (int)ROLE_TYPES.ENTERPRISE));
                        dic["service_register_examining_totalcount"] = G.DB.GetCount<Member>(string.Format("role_type = {0}", (int)ROLE_TYPES.SERVICE));
                        dic["member_totalcount"] = G.DB.GetCount<Member>();
                        dic["service_totalcount"] = G.DB.GetCount<ServiceItem>();
                        dic["demand_examining_totalcount"] = G.DB.GetCount<DemandItem>();
                        ResponseJson(new ObjectResult { data = dic });
                        break;
                    }
                default: break;
            }
        }

        public void Member(string action)
        {

            switch (action)
            {
                case "get":
                    {
                        Member member = G.DB.GetById<Member>(req_id);
                        ResponseJson(new ObjectResult { data = member });
                        break;
                    }
                case "status": // 注意这里不是修改status字段，是修改is_ban,is_delete。1解封，2封号，//3删除
                    {
                        CheckPermission(IDENTITY.ADMIN);
                        Member member = G.DB.GetById<Member>(req_id);
                        if (req_status == 1) member.is_ban = 0;
                        else if (req_status == 2) member.is_ban = 1;
                        //else if (req_status == 3) member.is_delete = 1;
                        G.DB.Update<Member>(member);
                        ResponseJson(new Result());
                        break;
                    }
                case "delete":
                    {
                        CheckPermission(IDENTITY.ADMIN, Permission.Module(PERMISSIONMODULE.MEMBER_MANAGE).Operation(PERMISSIONOPERATION.DELETE));
                        G.DB.Delete<Member>(req_id);
                        RecordLog("12", "删除了会员");
                        ResponseJson(new Result());
                        return;
                    }
                case "get_items":
                    {
                        string id = GetStringParam(new ReqStringParamOption { Name = "id" });
                        Cd cd = new Cd();
                        cd.And("member_id = '{0}'", id);
                        cd.And("status=2");
                        Ob ob = new Ob();
                        ob.Desc("id");
                        ResponseJson(GetPageResult<ServiceItem>(cd.Render(), ob.Render()));
                        break;
                    }
               
                  
                case "get_item":
                    {
                        string id = GetStringParam(new ReqStringParamOption { Name = "id" });
                        Cd cd = new Cd();
                        cd.And("member_id='{0}'", id);
                        cd.And("status=2");
                        Ob ob = new Ob();
                        ob.Desc("id");
                        ResponseJson(GetPageResult<DemandItem>(cd.Render(), ob.Render()));
                        break;
                    }
                case "login":
                    {
                        string validate_code = ctx.Session["validate_code"].ToString();
                        string code = GetStringParam(new ReqStringParamOption { Name = "validate_code" }).ToUpper();
                        MessageResult mes = new MessageResult();
                        if (code.Equals(validate_code))
                        {
                            ResponseJson(Login(IDENTITY.MEMBER));
                        }
                        else
                        {
                            ResponseJson(new BooleanResult { value = false, message = "验证码错误" });
                        }
                        break;
                    }
                    
                case "logout":
                    {
                        Logout();
                        ResponseJson(new Result());
                        break;
                    }
                    
                case "check_username":
                    {
                        string name = GetStringParam(new ReqStringParamOption { Name = "name" });
                        
                        if (check_username(name))
                        {
                            ResponseJson(new BooleanResult { value = true });
                        }
                        else
                        {
                            ResponseJson(new BooleanResult { value = false });
                        }

                        break;
                    }
                    
                //注册操作
                case "register":
                    {
                        if (check_phonenumber(req_mobile_phone))
                        {
                            if (check_username(req_username))
                            {
                                if ("success".Equals(ctx.Session["checkcodestatus"].ToString()))
                                {
                                    Member member = new Member();
                                    string phone = ctx.Session["auth_mobile_phone"].ToString();
                                    member.username = req_username;
                                    member.h_mobile_phone = req_mobile_phone;
                                    member.password = HashHelper.Hash_MD5_16(req_password);
                                    member.role_type = req_role_type;
                                    
                                    member.create_time = DateTimeEx.GetNowTimeStamp();
                                    member.is_mobile_phone_authed = true;
                                    member.special_permission = "+100010";
                                    member.status = 0;
                                    member.is_ban = 0;
                                    if (member.h_mobile_phone.Equals(phone))
                                    {
                                        if (G.DB.Insert<Member>(member) > 0)
                                        {
                                            ctx.Session["auth_code"] = null;
                                            ctx.Session.Remove("auth_code");
                                            switch (member.role_type)
                                            {
                                                case 3:
                                                    {
                                                        member.number = "p" + member.id;
                                                        break;
                                                    }
                                                case 4:
                                                    {
                                                        member.number = "c" + member.id;
                                                        break;
                                                    }
                                                case 5:
                                                    {
                                                        member.number = "a" + member.id;
                                                        break;
                                                    }

                                            }
                                            G.DB.Update<Member>(member);
                                            RecordLog(PERMISSIONOPERATION.REGISTER, req_username + "注册成功！");
                                            ResponseJson(new BooleanResult { value = true });
                                        }
                                        else
                                        {
                                            RecordLog(PERMISSIONOPERATION.REGISTER, req_username + "注册失败！原因：数据库操作错误！");
                                            ResponseJson(new BooleanResult { value = false, message = "" });
                                        }
                                    }
                                    else
                                    {
                                        RecordLog(PERMISSIONOPERATION.REGISTER, req_username + "注册失败！原因：非法修改电话号码！");
                                        ResponseJson(new BooleanResult { value = false, message = "电话号码已更改!!!" });
                                    }
                                }
                                else
                                {
                                    RecordLog(PERMISSIONOPERATION.REGISTER, req_username + "注册失败！原因：未验证电话号码！");
                                    ResponseJson(new BooleanResult { value = false, message = "未验证电话号码!!!" });
                                }
                            }
                            else
                            {
                                RecordLog(PERMISSIONOPERATION.REGISTER, req_username + "注册失败！原因：该用户名已被注册！");
                                ResponseJson(new BooleanResult { value = false, message = "该用户名已被注册!!!" });
                            }
                        }
                        else
                        {
                            RecordLog(PERMISSIONOPERATION.REGISTER, req_username + "注册失败！原因：该手机号已被注册！");
                            ResponseJson(new BooleanResult { value = false, message = "该手机号已被注册!!!" });
                        }
                        break;
                    }
                case "validate_code":
                    {
                        string validateCode = codevalidate.GenerateCheckCode();
                        ctx.Session["validate_code"] = validateCode;
                        ResponseJson(new ValueResult { value = codevalidate.CreateCheckCodeImage(validateCode) });
                        break;
                    }
                case "get_gsxt_info":
                    {
                        string enterprise_name = GetStringParam(new ReqStringParamOption { Name = "enterprise_name" });
                        GSInfo gs_info = GSXTHelper.GetByFullName(enterprise_name);

                        if(gs_info == null)
                        {
                            ThrowStatus(STATUS.FAILED_UPDATE, "无法在《国家企业信用信息公示系统》查询到您的企业信息！");
                        }
                        else
                        {
                            ResponseJson(new ObjectResult
                            {
                                data = new
                                {
                                    usci = gs_info.creditcode,
                                    registered_capital = (int)gs_info.money.ChangeType(typeof(int)),
                                    business_licence = gs_info.gongsh
                                }
                            });
                        }
                        break;
                    }
                case "update_me":
                    {
                        Member member = G.DB.GetById<Member>(req_id);
                        GSInfo gs_info = null;
                        if(member.role_type == (int)ROLE_TYPES.ENTERPRISE || member.role_type == (int)ROLE_TYPES.SERVICE)
                        {
                            string enterprise_name = GetStringParam(new ReqStringParamOption { Name = "enterprise_name" });
                            // 验证该企业是否已经注册
                            if(G.DB.IsOne<Member>(new Cd("id <> {0} and enterprise_name = '{1}'", member.id, enterprise_name).Render()))
                            {
                                ThrowStatus(STATUS.FAILED_UPDATE, "该企业已经注册！");
                            }
                            // 验证该企业是否在工商局可以查到
                            //gs_info = GSXTHelper.GetByFullName(enterprise_name);
                            //if(gs_info == null)
                            //{  
                            //    ThrowStatus(STATUS.FAILED_UPDATE, "无法在《国家企业信用信息公示系统》查询到您的企业信息！");
                            //}
                        }
                        ApplyMemberValue(member, gs_info);
                        member.status = 1;
                        G.DB.Update<Member>(member);
                        ResponseJson(new ValueResult { value = member.status });
                        break;
                    }
                // 用户自己修改密码
                case "update_pwd":
                    {
                        string old_password = GetStringParam(new ReqStringParamOption { Name = "old_password" });
                        string new_password = GetStringParam(new ReqStringParamOption { Name = "new_password" });
                        Member member = G.DB.GetById<Member>(UserCode);
                        if (HashHelper.Hash_MD5_16(old_password) == member.password)
                        {
                            member.password = HashHelper.Hash_MD5_16(new_password);
                            G.DB.Update<Member>(member);
                            ResponseJson(new Result());
                        }
                        else
                        {
                            ThrowStatus(STATUS.FAILED_UPDATE, "原始密码输入错误，密码重置失败");
                        }
                        break;
                    }
                case "retrievepwd":
                    {
                        Cd cd = new Cd("username='{0}'", ctx.Session["username"].ToString());
                        Member member = G.DB.Get<Member>(cd.Render()).GetFirstEntity();
                        member.password = req_password;

                        if (G.DB.Update<Member>(member) > 0)
                        {
                            ResponseJson(new BooleanResult { value = true });
                            RecordLog(PERMISSIONOPERATION.FINDBACKPASSWORD, ctx.Session["username"].ToString() + "找回密码成功");
                        }
                        else
                        {
                            ResponseJson(new BooleanResult { value = false, message = "未知错误密码修改失败" });
                        }
                        break;
                    }//电话找回密码修改
                case "retrievejudge":
                    {
                        {
                            String username = GetStringParam(new ReqStringParamOption { Name = "username" });
                            String userphone = GetStringParam(new ReqStringParamOption { Name = "userphone" });
                            Cd cd = new Cd();
                            cd.And("username='{0}'", username);
                            cd.And("mobile_phone='{0}'", userphone);
                            Member member = G.DB.Get<Member>(cd.Render()).GetFirstEntity();
                            if (member != null)
                            {
                                ResponseJson(new BooleanResult { value = true });
                                ctx.Session["username"] = username;

                            }
                            else
                            {
                                ResponseJson(new BooleanResult { value = false, message = "用户名或电话错误" });
                            }
                        }
                        break;
                    }
                case "change_phone":
                    {
                        if ("success".Equals(ctx.Session["checkcodestatus"].ToString()))
                        {
                            String phone = GetStringParam(new ReqStringParamOption { Name = "newPhone" });
                            Member member = G.DB.GetById<Member>(req_id);
                            member.h_mobile_phone = phone;
                            if (G.DB.Update<Member>(member) > 0)
                            {
                                ResponseJson(new BooleanResult { value = true, message = "更新成功" });
                            }
                            else
                            {
                                ResponseJson(new BooleanResult { value = false, message = "更新失败" });
                            }


                        }
                        else
                        {
                            ResponseJson(new BooleanResult { value = false, message = "非法操作" });
                        }
                        break;
                    }
                case "change_phone_byEmail":
                    {
                        string userName = GetStringParam(new ReqStringParamOption { Name = "name" });
                        string emailTo = G.DB.GetById<Member>(req_id).h_email;
                        string theme = "邮箱认证邮件";
                        string checkcode = MessageHelper.GetCode();
                        ctx.Session["auth_code"] = checkcode;
                        string sendTime = DateTimeEx.DateTimeToTimeStamp(DateTime.Now);
                        ctx.Session["get_auth_code_time"] = sendTime;
                        string body = "您好:" + userName + "<br>您正在通过邮箱修改您在本站绑定的手机号码，这是您的验证邮件，您的验证码如下：" + checkcode + "。<br>此验证码十分钟内有效，超过10分钟请重新到我站获取。<br>";   //内容
                        MemberMessage mm = SendEmail(int.Parse(UserCode), theme, body, emailTo);
                        if (mm.status != 9)
                        {
                            ResponseJson(new BooleanResult { value = true, message = "邮件发送成功,请您查收以获取验证码！" });
                        }
                        else
                        {
                            ResponseJson(new BooleanResult { value = false, message = "邮件发送失败！" });
                        }
                        break;
                    }
                //case "check":
                //    {
                //        GSInfo gs_info = GSXTHelper.GetByFullName(req_name);
                //        if(gs_info == null)
                //        {
                //            throw
                //        }
                //    }
                default: break;
            }
        }

        public void Me(string action)
        {
            switch (action)
            {
                case "get_info":
                    if (HasPermission(IDENTITY.ADMIN))
                    {
                        Admin admin = G.DB.GetById<Admin>(UserCode);
                        ResponseJson(new ObjectResult { data = admin });
                    }
                    else if (HasPermission(IDENTITY.MEMBER))
                    {
                        ResponseJson(new ObjectResult { data = G.DB.GetById<Member>(UserCode) });
                    }
                    else
                    {
                        ThrowStatus(STATUS.HASNOT_LOGIN, "检测不到身份，请重新登录！");
                    }
                    break;
                case "landing_state":
                    LANDINGSTATE landing_state = LandingServer.GetUnitState(UserIdentity + UserCode);
                    ResponseJson(new EnumResult { value = (int)landing_state, name = landing_state.ToString() });
                    break;
                default: break;
            }
        }

        private void ApplyMemberValue(Member member, GSInfo gs_info)
        {
            member.name = req_name;
            member.h_mobile_phone = req_mobile_phone;
            member.department = GetStringParam(new ReqStringParamOption { Name = "department" });
            member.area = GetStringParam(new ReqStringParamOption { Name = "area" });
            member.address = GetStringParam(new ReqStringParamOption { Name = "address" });
            member.identity_card = GetStringParam(new ReqStringParamOption { Name = "identity_card" });
            member.coordinate = GetStringParam(new ReqStringParamOption { Name = "coordinate" });
            if (member.role_type == (int)ROLE_TYPES.ENTERPRISE || member.role_type == (int)ROLE_TYPES.SERVICE)
            {
                member.enterprise_name = GetStringParam(new ReqStringParamOption { Name = "enterprise_name" });
                if(gs_info != null)
                {
                    member.usci = gs_info.creditcode;
                    member.registered_capital = (int)gs_info.money.ChangeType(typeof(int));
                    member.business_licence = gs_info.gongsh;
                }
                else
                {
                    member.usci = GetStringParam(new ReqStringParamOption { Name = "usci" });
                    member.registered_capital = GetIntParam(new ReqIntParamOption { Name = "registered_capital", Level = REQPARAMLEVEL.FREE });
                    member.business_licence = GetStringParam(new ReqStringParamOption { Name = "business_licence" });
                }
                member.enterprise_profile = GetStringParam(new ReqStringParamOption { Name = "enterprise_profile" });
                member.business_licence_pic = GetImageUrl(GetStringParam(new ReqStringParamOption { Name = "business_licence_pic" }), "营业执照");
                member.member_type = GetStringParam(new ReqStringParamOption { Name = "member_type" });
                member.logo = GetImageUrl(req_logo, "logo");
            }
        }

        public void authEmail(string action)
        {
            Email emailMes = G.DB.Get<Email>(new Cd().And("selected = 1").Render()).GetFirstEntity();
            switch (action)
            {
                //case "send_email_message":
                //    {
                        
                //        string Email = "fanzhiyuan1994@163.com";
                //        string title = GetStringParam(new ReqStringParamOption { Name = "email_title" ,Level = REQPARAMLEVEL.FREE});
                //        string content = GetStringParam(new ReqStringParamOption { Name = "email_content" ,Level = REQPARAMLEVEL.FREE});
                //        Template temp = new Template();
                //        MemberMessage mm = new MemberMessage();
                //        mm = SendEmail(title, content, Email);
                //        ResponseJson(new MessageResult { message = mm.content });
                //        break;
                //    }
                case "valid_email":
                    {
                        string email = GetStringParam(new ReqStringParamOption { Name = "email" });
                        int type_2 = GetIntParam(new ReqIntParamOption { Name = "type_2" });
                        Member m = G.DB.GetById<Member>(UserCode);
                        string name = m.username;
                        ResponseJson(new BooleanResult { value = EditEmail(type_2, email ,name) });
                        break;
                    }
                //case "valid_email":
                //    {
                //        string email_to = GetStringParam(new ReqStringParamOption { Name = "email" });
                //        int type_2 = GetIntParam(new ReqIntParamOption { Name = "type_2" });
                //        string title = "";
                //        string body = "";

                //        switch (type_2)
                //        {
                //            case 1:
                //                {
                //                    Template temp = G.DB.Get<Template>(new Cd().And("type_2 = 1").And("type_1 = 'email'").And("selected = '1'").Render()).GetFirstEntity();

                //                    Dictionary<string, object> dic = LandingServer.GetDictionary(UserCode);
                //                    if (temp != null)
                //                    {
                //                        title = temp.title;
                //                        body = temp.content;
                //                        string reg = "/${(?<key>.*?)}";
                //                        Regex r = new Regex(reg, RegexOptions.None);
                //                        MatchCollection mc = r.Matches(temp.content);
                //                        if (mc.Count > 0)
                //                        {
                //                            foreach (Match m in mc)
                //                            {
                //                                if (m.Value == "code")
                //                                {
                //                                    string code = MessageHelper.GetCode();
                //                                    string sendTime = DateTimeEx.DateTimeToTimeStamp(DateTime.Now);
                //                                    body.Replace("${code}", "< a href =\"http://" + FreeValue.GetValue("website.domain") + "/#/emailAuth?id=" + UserCode + "&code=" + code + "&time=" + sendTime + "&email=" + email_to + "\">邮箱认证链接</a>");
                //                                    dic["email"] = email_to;
                //                                    dic["send_time"] = sendTime;
                //                                    dic["code"] = code;
                //                                }
                //                                else
                //                                {
                //                                    FreeValue fv = G.DB.Get<FreeValue>(new Cd().And("_key = '{0}'", m.Value).Render()).GetFirstEntity();
                //                                    if (fv != null)
                //                                    {
                //                                        body.Replace("${" + m.Value + "}", fv.value);
                //                                    }
                //                                    else
                //                                    {
                //                                        ThrowStatus(STATUS.NO_PERMISSION, "未设置变量[" + m.Value + "]");
                //                                    }
                //                                }
                //                            }
                //                        }
                                        
                //                        MemberMessage mm = SendEmail(int.Parse(UserCode), title, body, email_to);
                //                        if (mm.status != 9)
                //                        {
                //                            ResponseJson(new BooleanResult { value = true, message = "邮件发送成功！" });
                //                        }
                //                        else
                //                        {
                //                            ResponseJson(new BooleanResult { value = false, message = "邮件发送失败！" });
                //                        }
                //                    }
                //                    else
                //                    {
                //                        ThrowStatus(STATUS.NO_PERMISSION, "未设置启用模板");
                //                        ResponseJson(new BooleanResult { value = false, message = "系统设置错误" });
                //                    }
                //                    break;
                //                }
                //            case 2:
                //                {

                //                    break;
                //                }
                //            case 3:
                //                {
                //                    Template temp = G.DB.Get<Template>(new Cd().And("type_2 = 3").And("type_1 = 'email'").And("selected = '1'").Render()).GetFirstEntity();

                //                    Dictionary<string, object> dic = LandingServer.GetDictionary(UserCode);
                //                    if (temp != null)
                //                    {
                //                        title = temp.title;
                //                        string[] str = temp.content.Split('$');
                //                        string code = MessageHelper.GetCode();
                //                        string sendTime = DateTimeEx.DateTimeToTimeStamp(DateTime.Now);
                //                        body = body + str[0];
                //                        for (int i = 1; i < str.Length; i++)
                //                        {
                //                            string variable = str[i].Substring(0, str[i].IndexOf('}'));
                //                            if (variable != "")
                //                            {
                //                                variable = variable.Replace("{", "").Replace("{", "");
                //                                FreeValue fv = G.DB.Get<FreeValue>(new Cd().And("_key = '{0}'", variable).Render()).GetFirstEntity();
                //                                if (variable == "code")
                //                                {
                //                                    str[i] = "< a href =\"http://" + FreeValue.GetValue("website.domain") + "/#/emailAuth?id=" + UserCode + "&code=" + code + "&time=" + sendTime + "&email=" + email_to + "\">邮箱认证链接</a>" + str[i].Substring(str[i].IndexOf('}')).Replace("}", "");
                //                                }
                //                                else if (fv != null)
                //                                {
                //                                    str[i] = fv.value + str[i].Substring(str[i].IndexOf('}'));
                //                                }
                //                                else
                //                                {
                //                                    ThrowStatus(STATUS.NO_PERMISSION, "未设置变量[" + variable + "]");
                //                                }
                //                            }
                //                            body += str[i];
                //                        }
                //                        dic["email"] = email_to;
                //                        dic["send_time"] = sendTime;
                //                        dic["code"] = code;
                //                        MemberMessage mm = SendEmail(int.Parse(UserCode), title, body, email_to);
                //                        if (mm.status != 9)
                //                        {
                //                            ResponseJson(new BooleanResult { value = true, message = "邮件发送成功！" });
                //                        }
                //                        else
                //                        {
                //                            ResponseJson(new BooleanResult { value = false, message = "邮件发送失败！" });
                //                        }
                //                    }
                //                    else
                //                    {
                //                        ThrowStatus(STATUS.NO_PERMISSION, "未设置启用模板");
                //                        ResponseJson(new BooleanResult { value = false, message = "系统设置错误" });
                //                    }
                //                    break;
                //                    break;
                //                }
                //        }
                //        break;
                //    }
                case "apply_auth":
                    {
                        Member member = G.DB.GetById<Member>(req_id);
                        string email = GetStringParam(new ReqStringParamOption { Name = "email" });
                        string userName = GetStringParam(new ReqStringParamOption { Name = "name" });
                        bool is_change_email = GetBooleanParam(new ReqBooleanParamOption { Name = "is_change_email" });
                        string emailTo = "";
                        if (member.is_email_authed == false || is_change_email == true)
                        {
                            emailTo = email;
                        }
                        else
                        {
                            emailTo = member.h_email;
                        }
                        string theme = "邮箱认证邮件";
                        string code = MessageHelper.GetCode();
                        string sendTime = DateTimeEx.DateTimeToTimeStamp(DateTime.Now);
                        Dictionary<string, object> dic = LandingServer.GetDictionary(UserCode);
                        dic["email"] = email;
                        dic["send_time"] = sendTime;
                        dic["code"] = code;
                        string body = "您好:" + userName + "<br>感谢您在我站绑定邮箱账号，这是您的验证邮件。<br>请点击一下链接确定认证，如非您本人操作请不要点击链接<a href=\"https://" + FreeValue.GetValue("website.domain") + "/#/emailAuth?id=" + req_id + "&code=" + code + "&time=" + sendTime + "&email=" + email + "\">邮箱认证链接</a><br>本链接十分钟内有效，超过10分钟请重新到我站点击认证获取。<br>";   //内容
                        MemberMessage mm = SendEmail( int.Parse(UserCode), theme, body, emailTo);
                        if (mm.status != 9)
                        {
                            ResponseJson(new BooleanResult { value = true, message = "邮件发送成功！" });
                        }
                        else
                        {
                            ResponseJson(new BooleanResult { value = false, message = "邮件发送失败！" });
                        }
                        break;
                    }
                case "check_email":
                    {
                        string new_code = GetStringParam(new ReqStringParamOption { Name = "code" });
                        Member member = G.DB.GetById<Member>(req_id);
                        Dictionary<string, object> dic = LandingServer.GetDictionary(member.id.ToString());
                        BooleanResult br = new BooleanResult { value = false, message = "邮箱认证失败" };
                        if(dic != null && dic.ContainsKey("email") && dic.ContainsKey("send_time") && dic.ContainsKey("code"))
                        {
                            string send_time = dic["send_time"].ToString();
                            string now_time = DateTimeEx.DateTimeToTimeStamp(DateTime.Now.AddMinutes(-10));
                            if (string.Compare(now_time, send_time) < 0)
                            {
                                if (dic["code"].ToString() == new_code)
                                {
                                    member.is_email_authed = true;
                                    member.h_email = dic["email"].ToString();
                                    G.DB.Update<Member>(member);
                                    br.value = true;
                                    br.message = " 邮箱认证成功";
                                }
                            }
                            else
                            {
                                br.message = "链接已过期";
                            }
                        }
                        ResponseJson(br);
                        break;
                    }
                case "check_old_email":
                    {
                        string wholeEmail = GetStringParam(new ReqStringParamOption { Name = "whole_email" });
                        string email = (G.DB.GetById<Member>(req_id)).h_email;
                        if (wholeEmail == email)
                        {
                            ResponseJson(new BooleanResult { value = true, message = "邮箱正确！" });
                        }
                        else
                        {
                            ResponseJson(new BooleanResult { value = false, message = "填写错误，请重新填写！" });
                        }
                        break;
                    }
                default: break;
            }
        }
        public bool check_username(string name)
        {
            Cd cd = new Cd();
            cd.And("username='{0}'", name);
            int res = G.DB.GetCount<Member>(cd.Render());
            if (res == 0)
            {
                return true;
            }
            return false;
        }
        public bool check_phonenumber(string num)
        {
            Cd cd = new Cd();
            cd.And("mobile_phone='{0}'", num);
            int res = G.DB.GetCount<Member>(cd.Render());
            if (res == 0)
            {
                return true;
            }
            return false;
        }

        public UploadedFile Base64ToImage(string base64Data, string file_name)
        {
            base64Data = Regex.Replace(base64Data, @"^data:image\/\w+;base64,", "");
            byte[] arr = Convert.FromBase64String(base64Data);
            UploadedFile ur = new ApiUpload(this.ctx).SaveFile(arr, file_name + ".png");
            return ur;
            //using (MemoryStream ms = new MemoryStream(arr))
            //{
                //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms);
                ////只有把当前的图像复制一份，然后把旧的Dispose掉，那个文件就不被锁住了，
                ////这样就可以放心覆盖原始文件，否则GDI+一般性错误(A generic error occurred in GDI+)
                //System.Drawing.Bitmap bmpNew = new System.Drawing.Bitmap(bmp2);
                //bmp.Dispose();
                //bmp = null;
                //bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                //bmp.Save(filePath + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                //bmp.Save(filePath + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                //bmp.Save(filePath + ".gif", System.Drawing.Imaging.ImageFormat.Gif);
                //bmp.Save(filePath + ".png", System.Drawing.Imaging.ImageFormat.Png);
                //bmp.Dispose();
            //}
        }

        public string GetImageUrl(string dataUrl, string file_name)
        {
            if(Regex.IsMatch( dataUrl, @"^data:image\/\w+;base64,"))
            {
                return Base64ToImage(dataUrl, file_name).url;
            }else
            {
                return dataUrl;
            }
        }
    }
}